package com.retail.lottery.colalottery.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.retail.lottery.colalottery.entity.ColaAnswerRecord;
import com.retail.lottery.colalottery.entity.ColaQuestionBank;
import com.retail.lottery.colalottery.enums.IsPassEnum;
import com.retail.lottery.colalottery.mapper.ColaAnswerRecordMapper;
import com.retail.lottery.colalottery.service.ColaAnswerRecordService;
import com.retail.lottery.colalottery.service.QuestionCommonCacheService;
import com.retail.lottery.colalottery.utils.CommonRedisKeyUtils;
import com.retail.lottery.colalottery.vo.request.QuestionAnswerListRequest;
import com.retail.lottery.colalottery.vo.request.QuestionAnswerRequest;
import com.retail.lottery.colalottery.vo.response.ColaQuestionAnswerRecordVo;
import com.retail.lottery.colalottery.vo.response.ColaQuestionAnswerResultVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author jarvis.zhang
 * @description 针对表【cola_answer_record(可乐答题记录表)】的数据库操作Service实现
 * @createDate 2025-06-17 13:41:24
 */
@Service
public class ColaAnswerRecordServiceImpl extends ServiceImpl<ColaAnswerRecordMapper, ColaAnswerRecord> implements ColaAnswerRecordService {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private QuestionCommonCacheService questionCommonCacheService;


    @Override
    public ColaQuestionAnswerResultVo answerQuestion(QuestionAnswerRequest answer) {
        // 1.判断答题是否对
        ColaQuestionAnswerResultVo resultVo = new ColaQuestionAnswerResultVo();
        ColaQuestionBank colaQuestionBank = questionCommonCacheService.queryColaQuestionBankById(answer.getBuCode(), answer.getSetupId(), answer.getQuestionId());
        if (ObjectUtil.isNotEmpty(colaQuestionBank)) {
            if (!colaQuestionBank.getOptionAnswer().equals(answer.getAnswerOptionType())) {
                // 答题错误--不留档任何信息，提示错误即可
                return new ColaQuestionAnswerResultVo(Boolean.FALSE);
            }
        }
        // 2.查询当前用户是否已通过考试
        boolean isPass = questionCommonCacheService.queryCustomerAnswerResult(answer.getQuestionId(), answer.getOpenId(), answer.getOneid());
        if (ObjectUtil.isNotEmpty(isPass) && isPass) {
            // 已考过且答对---只记录一次答题结果
            return new ColaQuestionAnswerResultVo(Boolean.TRUE, colaQuestionBank.getAnswerTip());
        }
        // 3.如果历史没有答对过，保存答题成功记录
        ColaAnswerRecord colaAnswerRecord = new ColaAnswerRecord();
        colaAnswerRecord.setIsPass(IsPassEnum.SUCC.getCode());
        colaAnswerRecord.setQuestionId(answer.getQuestionId());
        colaAnswerRecord.setBuCode(answer.getBuCode());
        colaAnswerRecord.setSetupId(answer.getSetupId());
        colaAnswerRecord.setQuestionAnswer(answer.getAnswerOptionType());
        colaAnswerRecord.setOneid(answer.getOneid());
        colaAnswerRecord.setOpenId(answer.getOpenId());
        baseMapper.insert(colaAnswerRecord);
        // 4.清空答题结果的缓存
        try {
            String redisKey = CommonRedisKeyUtils.getCustomerAnswerCacheKey(answer.getQuestionId(), answer.getOpenId(), answer.getOneid());
            String answerHistoryCacheKey = CommonRedisKeyUtils.getCustomerAnswerHistoryCacheKey(answer.getBuCode(), answer.getSetupId(), answer.getOpenId(), answer.getOneid());
            redisTemplate.delete(Arrays.asList(redisKey, answerHistoryCacheKey));
        } catch (Exception e) {
            log.error("缓存清除策略异常", e);
        }
        return new ColaQuestionAnswerResultVo(Boolean.TRUE, colaQuestionBank.getAnswerTip());
    }

    @Override
    public List<ColaQuestionAnswerRecordVo> answerHistory(QuestionAnswerListRequest answerRequest) {
        if (StringUtils.isBlank(answerRequest.getOneid())) {
            return Collections.emptyList();
        }
        // 1.查询缓存数据是否为最新数据
        String redisKey = CommonRedisKeyUtils.getCustomerAnswerHistoryCacheKey(answerRequest.getBuCode()
                , answerRequest.getSetupId(), answerRequest.getOpenId(), answerRequest.getOneid());
        Object colaAnswerRecordListCacheInfo = redisTemplate.opsForValue().get(redisKey);
        List<ColaQuestionAnswerRecordVo> colaAnswerRecordList = new ArrayList<>();
        if (ObjectUtil.isEmpty(colaAnswerRecordListCacheInfo)) {
            List<ColaAnswerRecord> colaAnswerRecordDbList = this.baseMapper.queryAnswerResultList(answerRequest.getBuCode()
                    , answerRequest.getSetupId(), answerRequest.getOpenId(), answerRequest.getOneid());
            if (CollectionUtil.isNotEmpty(colaAnswerRecordDbList)) {
                for (ColaAnswerRecord colaAnswerRecord : colaAnswerRecordDbList) {
                    ColaQuestionAnswerRecordVo recordVo = new ColaQuestionAnswerRecordVo();
                    recordVo.setAnswerNum(1);
                    recordVo.setAnswerTime(colaAnswerRecord.getCreationDate());
                    recordVo.setAnswerResult(ObjectUtils.isEmpty(colaAnswerRecord)
                            || ObjectUtils.isEmpty(colaAnswerRecord.getIsPass())
                            || colaAnswerRecord.getIsPass() == IsPassEnum.FAIL.getCode()
                            ? Boolean.FALSE : Boolean.TRUE);
                    colaAnswerRecordList.add(recordVo);
                }
            }
            try {
                redisTemplate.opsForValue().set(redisKey, JSONUtil.toJsonStr(colaAnswerRecordList), 5, TimeUnit.MINUTES);
            } catch (Exception e) {
                log.error("每周题目封装异常", e);
            }
        } else {
            colaAnswerRecordList = JSONUtil.toList(JSONUtil.toJsonStr(colaAnswerRecordListCacheInfo), ColaQuestionAnswerRecordVo.class);
        }
        return colaAnswerRecordList;
    }


}




